package cn.micai.base.concurrent;

/**
 * @author zhaoxinguo on 2018/5/12.
 * @email sxdtzhaoxinguo@163.com
 * @qq 827358369
 * @phone 18611966723
 * @description 这是个使用ThreadLocal的例子，每个线程产生自己独立的序号。
 * 就是使用ThreadLocal存储每个线程独立的序列号复本，线程之间互不干扰.
 */
public class ThreadLocalTest {

    // 定义匿名子类创建ThreadLocal的变量
    private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>(){
        // 覆盖初始化方法
        public Integer initialValue() {
            return 0;
        }
    };

    // 下一个序列号
    public int getNextNum() {
        seqNum.set(seqNum.get() + 1);
        return seqNum.get();
    }

    private static class TestClient extends Thread {
        private ThreadLocalTest threadLocalTest;
        public TestClient(ThreadLocalTest threadLocalTest) {
            this.threadLocalTest = threadLocalTest;
        }
        // 线程产生序列号
        @Override
        public void run() {
            for (int i=0; i<3; i++) {
                System.out.println("thread[" + Thread.currentThread().getName() + "] " +
                        "threadLocalTest[" + threadLocalTest.getNextNum() + "]");
            }
        }
    }

    public static void main(String [] args) {
        ThreadLocalTest threadLocalTest = new ThreadLocalTest();
        // 三个线程产生各自的序列号
        TestClient t1 = new TestClient(threadLocalTest);
        TestClient t2 = new TestClient(threadLocalTest);
        TestClient t3 = new TestClient(threadLocalTest);
        t1.start();
        t2.start();
        t3.start();
    }
}
